<template>
  <div class="page-user">
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="nickName"
            :label="$t('users.name') + ':'"
          >
            <el-input
              v-model="searchForm.nickName"
              type="text"
              :placeholder="$t('users.name')"
            />
          </el-form-item>
          <el-form-item
            prop="userMobile"
            :label="$t('publics.mobilePhone') + ':'"
          >
            <el-input
              v-model="searchForm.userMobile"
              type="text"
              :placeholder="$t('publics.mobilePhone')"
            />
          </el-form-item>
          <el-form-item
            prop="levelType"
            :label="$t('user.memberType') + ':'"
          >
            <el-cascader
              ref="memberCascaderRef"
              v-model="memberLevelVal"
              :options="levelTypes"
              :props="{ checkStrictly: true }"
              clearable
              @change="onHandleMemberTypeChange"
            />
          </el-form-item>
          <el-form-item
            prop="status"
            :label="$t('publics.status') + ':'"
          >
            <el-select
              v-model="searchForm.status"
              :placeholder="$t('publics.status')"
            >
              <el-option
                :label="$t('publics.disable')"
                :value="0"
              />
              <el-option
                :label="$t('publics.normal')"
                :value="1"
              />
            </el-select>
          </el-form-item>
          <!-- 会员标签 -->
          <el-form-item
            :label="$t('user.userTag') + ':'"
            prop="userTag"
          >
            <el-select
              v-model="searchForm.userTag"
              v-el-select-loadmore="onLoadMore"
              multiple
              clearable
              collapse-tags
              :placeholder="$t('user.userTagDefaultTxt')"
            >
              <el-option
                v-for="item in tagList1"
                :key="item.userTagId"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch(searchFormRef)"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <div class="main-container">
      <div class="operation-bar">
        <el-checkbox
          v-model="selectAll"
          class="all-check-btn"
          @change="onSelectAll"
        >
          {{
            $t('publics.selectAll')
          }}
        </el-checkbox>
        <span
          v-if="dataListSelections.length"
          class="had-selected"
        >{{ $t('brand.selected') }} {{ dataListSelections.length }}</span>
        <el-button
          v-if="isAuth('admin:user:import')"
          type="primary"
          @click="onImportUser()"
        >
          {{ $t('user.userImport') }}
        </el-button>
        <el-button
          v-if="isAuth('admin:user:import')"
          type="primary"
          @click="onExportUser()"
        >
          {{ $t('user.export') }}
        </el-button>
        <div
          style="display: inline-block"
          @click="showBatchSetting = true"
        >
          <el-dropdown
            class="batch-setting-dropdown"
            :hide-on-click="false"
            trigger="click"
            @command="onHandleBatchSetting"
            @visible-change="onHandleVisibleChange"
          >
            <el-button type="primary">
              {{ $t('publics.batchSetting') }}
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </el-button>
            <!-- 批量设置功能列表 -->
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-if="isAuth('user:userLevel:updateGrowth')"
                  command="0"
                >
                  {{
                    $t('user.updateGrowth')
                  }}
                </el-dropdown-item>
                <el-dropdown-item command="1">
                  {{ $t('user.tagging') }}
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="isAuth('user:userLevel:updateScore')"
                  command="2"
                >
                  {{
                    $t('user.updateScore')
                  }}
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="isAuth('admin:coupon:sendUserCoupon')"
                  command="3"
                >
                  {{
                    $t('user.sendCoupons')
                  }}
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="isAuth('user:userBalance:updateBalance')"
                  command="4"
                >
                  {{
                    $t('user.modifyBalance')
                  }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-con user-table">
        <el-table
          ref="userListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @selection-change="onSelectSome"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            fixed
            prop="nickName"
            :label="$t('users.name')"
            width="130"
          >
            <template #default="scope">
              <span class="table-cell-text">{{ scope.row.nickName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed
            prop="pic"
            :label="$t('publics.profilePicture')"
            width="130"
          >
            <template #default="scope">
              <div class="table-cell-image">
                <img
                  v-if="!scope.row.pic"
                  alt=""
                  src="~@/assets/img/userImg.jpg"
                >
                <img
                  v-else
                  alt=""
                  :src="resourcesUrl +scope.row.pic"
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="userMobile"
            :label="$t('publics.mobilePhone')"
            width="130"
          />
          <el-table-column
            prop="levelName"
            :label="$t('user.membershipLevel')"
            width="130"
          />
          <el-table-column
            prop="levelType"
            :label="$t('user.memberType')"
            width="130"
          >
            <template #default="scope">
              <span
                v-if="scope.row.levelType === 0"
                class="tag-text"
              >{{
                $t('user.ordinaryMember')
              }}</span>
              <span
                v-else
                class="tag-text"
              >{{ $t('user.paidMembership') }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="score"
            :label="$t('user.userScore')"
            width="130"
          />
          <el-table-column
            prop="sumScore"
            :label="$t('user.cumulativeScore')"
            width="130"
          />
          <el-table-column
            prop="growth"
            :label="$t('user.growth')"
            width="130"
          />
          <el-table-column
            prop="status"
            :label="$t('publics.status')"
            width="130"
          >
            <template #default="scope">
              <span class="tag-text">{{
                [$t('publics.disable'), $t('publics.normal')][scope.row.status]
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="consAmount"
            :label="$t('user.consumptionAmount')"
            width="130"
          />
          <el-table-column
            prop="actualAmount"
            :label="$t('user.actuallypaid')"
            width="130"
          />
          <el-table-column
            prop="consTimes"
            :label="$t('user.consumptionTimes')"
            width="130"
          />
          <el-table-column
            prop="averDiscount"
            :label="$t('user.averageDiscount')"
            width="130"
          />
          <el-table-column
            prop="rechargeAmount"
            :label="$t('user.rechargeAmount')"
            width="130"
          />
          <el-table-column
            prop="rechargeTimes"
            :label="$t('user.rechargeTimes')"
            width="130"
          />
          <el-table-column
            prop="afterSaleAmount"
            :label="$t('home.refundAmount')"
            width="150"
          />
          <el-table-column
            prop="afterSaleTimes"
            :label="$t('user.refundTimes')"
            width="130"
          />
          <el-table-column
            prop="currentBalance"
            :label="$t('user.currentBalance')"
            width="130"
          />
          <el-table-column
            prop="sumBalance"
            :label="$t('user.cumulativeBalances')"
            width="130"
          />
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="180"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('admin:user:info')"
                  class="default-btn text-btn"
                  @click.stop="onAddOrUpdate(scope.row.userId)"
                >
                  {{ $t('coupon.edit') }}
                </div>
                <div
                  v-if="isAuth('user:userBalance:updateBalance')"
                  class="default-btn text-btn"
                  @click.stop="onUpdateBalance(scope.row.userId, 0, scope.row.currentBalance)"
                >
                  {{ $t('user.modifyBalance') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-growth
      v-if="updateGrowthVisible"
      ref="updateGrowthRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-score
      v-if="updateScoreVisible"
      ref="updateScoreRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-tags
      v-if="updateTagsVisible"
      ref="updateTagsRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-balance
      v-if="updateBalanceVisible"
      ref="updateBalanceRef"
      @refresh-data-list="refreshChange"
    />
    <update-user-coupon
      v-if="updateCouponVisible"
      ref="updateCouponRef"
      :get-way="1"
      @refresh-data-list="refreshChange"
    />
    <import-user-update
      v-if="importUserVisible"
      ref="importUserRef"
      @refresh-data-list1="refreshChange"
    />
  </div>
</template>

<script setup>
import AddOrUpdate from './add-or-update.vue'
import UpdateUserGrowth from './components/update-growth.vue'
import UpdateUserScore from './components/update-score.vue'
import UpdateUserTags from './components/update-tags.vue'
import UpdateUserBalance from './components/update-balance.vue'
import UpdateUserCoupon from './components/update-coupon.vue'
import ImportUserUpdate from './components/excel-user-import.vue'
import { ElMessage } from 'element-plus'
import { isAuth } from '@/utils/index'
const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL

const vElSelectLoadmore = {
  mounted: (el, binding) => {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
    SELECTWRAP_DOM?.addEventListener('scroll', function () {
      /**
       * scrollHeight 获取元素内容高度(只读)
       * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
       * clientHeight 读取元素的可见高度(只读)
       * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
       * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
       */
      const condition =
        document.documentElement.scrollHeight - document.documentElement.scrollTop <=
        document.documentElement.clientHeight + 0.5
      if (condition) {
        binding.value()
      }
    })
  }
}

let tempSearchForm = null // 保存上次点击查询的请求条件
const dataList = ref([])
const dataListLoading = ref(false)
const importDisabled = ref(false)
const updateBalanceVisible = ref(false)
const updateCouponVisible = ref(false)
const dataListSelections = ref([])
const addOrUpdateVisible = ref(false)
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = ref({
  tagIds: [],
  levelType: '',
  // 会员等级
  level: '',
  nickName: '',
  status: '',
  userMobile: ''
})
const selectAll = ref(false)
const showBatchSetting = ref(false)
const memberLevelVal = ref('')
const memberCascaderRef = ref(null)
const updateBalanceRef = ref(null)
const updateCouponRef = ref(null)
const userListTableRef = ref(null)
const searchFormRef = ref(null)
const levelTypes = ref([
  {
    label: $t('user.ordinaryMember'),
    value: 0,
    children: []
  },
  {
    label: $t('user.paidMembership'),
    value: 1,
    children: []
  }
])
// 会员标签列表
const tagList = ref([])
const tagTotal = ref(0)
const tagSearchParam = {
  size: 10,
  current: 1
}
onMounted(() => {
  onGetMemberLevelList()
  onGetDataList()
  onGetMemberTags()
})

/**
 * 切换付费会员等级
 */
const onHandleMemberTypeChange = val => {
  searchForm.value.levelType = val[0]
  searchForm.value.level = val[1] || ''
  memberCascaderRef.value.dropDownVisible = false
}
/**
 * 获取会员等级列表
 */
const onGetMemberLevelList = () => {
  for (let index = 0; index < 2; index++) {
    http({
      url: http.adornUrl('/user/userLevel/list'),
      method: 'get',
      params: http.adornParams({
        userLevelType: index
      })
    }).then(({ data }) => {
      const children = []
      data.forEach(el => {
        children.push({
          value: el.level,
          label: el.levelName
        })
      })
      levelTypes.value[index].children = children
    })
  }
}
// 获取数据列表
const onGetDataList = (pageParam, newData = false) => {
  dataListLoading.value = true
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm.value))
    delete tempSearchForm.userTag
  }
  http({
    url: http.adornUrl('/admin/user/userPage'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.value.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.value.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.value.total = data.total
    dataListLoading.value = false
  })
}
// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = id => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
// 条件查询 JSON.stringify(arr)
const onSearch = (newData = false) => {
  let arr = ''
  if (searchForm.value.userTag.length !== 0) {
    searchForm.value.userTag.forEach(item => {
      arr = arr + item + ','
    })
  }
  searchForm.value.tagIds = arr
  page.value.currentPage = 1
  onGetDataList(page.value, newData)
}
// 刷新回调用
const refreshChange = () => {
  onGetDataList(page.value)
}
// 多选变化
const onSelectSome = val => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length
}
// 修改成长值
const updateGrowthRef = ref(null)
const updateGrowthVisible = ref(false)
const onUpdateGrowth = id => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateGrowthVisible.value = true
  nextTick(() => {
    updateGrowthRef.value?.init(ids)
  })
}
// 修改成长值
const updateScoreVisible = ref(false)
const updateScoreRef = ref(null)

const onUpdateScore = id => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateScoreVisible.value = true
  nextTick(() => {
    updateScoreRef.value?.init(ids)
  })
}
const updateTagsRef = ref(null)
const updateTagsVisible = ref(false)
const onUpdateTags = id => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateTagsVisible.value = true
  nextTick(() => {
    updateTagsRef.value?.init(ids)
  })
}
// type 1 批次充值 0修改余额
const onUpdateBalance = (id, type, balance) => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateBalanceVisible.value = true
  nextTick(() => {
    updateBalanceRef.value?.init(ids, type, balance)
  })
}
const onUpdateCoupon = id => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.userId
  })
  updateCouponVisible.value = true
  nextTick(() => {
    updateCouponRef.value?.init(ids)
  })
}

/**
 * 导入用户
 */
const importUserVisible = ref(false)
const importUserRef = ref(null)
const onImportUser = () => {
  if (importDisabled.value) {
    return
  }
  importUserVisible.value = true
  nextTick(() => {
    importUserRef.value?.init()
  })
}
/**
 * 导出单品
 */
let exportDisabled = false
const onExportUser = () => {
  if (exportDisabled) {
    return
  }
  exportDisabled = true
  http({
    url: http.adornUrl('/admin/user/exportUser'),
    method: 'get',
    params: http.adornParams(searchForm.value),
    timeout: 1000 * 60 * 10,
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    exportDisabled = false
    const blob = new Blob([data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
    })
    const fileName = $t('product.userInfoTable') + '.xls'
    const elink = document.createElement('a')
    if ('download' in elink) {
      // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else {
      // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

/**
 * 全选按钮
 */
const onSelectAll = () => {
  selectAll.value = userListTableRef.value.selection?.length < dataList.value?.length
  userListTableRef.value?.toggleAllSelection()
}

/**
 * 批量设置菜单显隐
 */
const onHandleVisibleChange = val => {
  showBatchSetting.value = val
}

/**
 * 批量设置
 */
const onHandleBatchSetting = command => {
  if (!dataListSelections.value.length) {
    ElMessage.warning($t('user.selectUserTips'))
    return
  }
  if (command === '0') {
    onUpdateGrowth()
  } else if (command === '1') {
    onUpdateTags()
  } else if (command === '2') {
    onUpdateScore()
  } else if (command === '3') {
    onUpdateCoupon()
  } else if (command === '4') {
    onUpdateBalance(null, 1)
  }
}

/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const onResetSearch = formName => {
  formName.resetFields()
  searchForm.value.userTag = []
  memberLevelVal.value = null
}

const onPageSizeChange = val => {
  page.value.pageSize = val
  onGetDataList()
}
const onPageChange = val => {
  page.value.currentPage = val
  onGetDataList()
}
/**
 * 获取会员标签列表
 */
const tagList1 = ref([])
const onGetMemberTags = () => {
  http({
    url: http.adornUrl('/user/userTag/byTagType'),
    method: 'get',
    params: http.adornParams(tagSearchParam)
  }).then(({ data }) => {
    if (!data) return
    tagTotal.value = data.total
    tagList.value = [...tagList.value, ...data.records]
    tagList.value.forEach(item => {
      tagList1.value.push({
        label: item.tagName,
        value: item.userTagId
      })
    })
  })
}
const onLoadMore = () => {
  tagSearchParam.current++
  if (tagList1.value.length < tagTotal.value) {
    onGetMemberTags()
  }
}
</script>
<style lang="scss" scoped>
.page-user {
  .main-container {
    .operation-bar {
      .all-check-btn {
        margin-right: 10px;
      }
      .had-selected {
        font-size: 12px;
        margin-right: 10px;
      }
      .batch-setting-dropdown {
        margin-left: 10px;
      }
    }
  }
  :deep(.el-select .el-select__tags > span > .el-tag.el-tag--info:nth-last-child(2)) {
    max-width: 120px;
  }
}
</style>
